package com.study.jsqlparser;

import com.study.jsqlparser.dto.SlowQueryMetadata;
import com.study.jsqlparser.utils.FileUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class SlowQueryAnalysis {
    @SneakyThrows
    public static void main(String[] args) {
//        statistics4Directory();
        statistics4File();
    }


    /**
     * 对单个慢sql文件文件去重
     */
    private static void statistics4File() throws IOException {
        String fileFullName = "slow.log";
        // 去重后的sql文件
        String deduplicationFileFullName = "deduplication.log";
        File slowFile = new File(fileFullName);
        List<String> list = FileUtils.readFileByLine(slowFile);
        log.info("从文件中读取到的总行数:{}", list.size());
        List<SlowQueryMetadata> slowQueryMetadataList = getSqlDTOList(list, slowFile.getName());
        log.info("提取出了:{}条sql", slowQueryMetadataList.size());
        HashSet<SlowQueryMetadata> set = new HashSet<>(slowQueryMetadataList);
        log.info("去重后的sql条数:{}", set.size());
        List<String> deduplication = set.stream().sorted(Comparator.comparingInt(SlowQueryMetadata::getCount).reversed()).map(SlowQueryMetadata::toString).collect(Collectors.toList());
        FileUtils.write2File(new File(deduplicationFileFullName), deduplication);

    }


    /**
     * 对文件夹下所有慢sql文件去重
     */
    private static void statistics4Directory() throws IOException {
        String directoryFullName = "E:\\xinao\\sql优化\\0516慢SQL已分割\\sql\\";
        // 去重后的sql文件
        String deduplicationFileFullName = "deduplication.sql";
        Set<SlowQueryMetadata> set = new HashSet<>();
        for (File file : new File(directoryFullName).listFiles()) {
            String fileName = file.getName();
            log.info(fileName);
            List<String> list = FileUtils.readFileByLine(file);
            log.info("从文件中读取到的总行数:{}", list.size());
            List<SlowQueryMetadata> slowQueryMetadataList = getSqlDTOList(list, fileName);
            log.info("提取出了:{}条sql", slowQueryMetadataList.size());
            set.addAll(slowQueryMetadataList);
        }
        log.info("去重后的sql条数:{}", set.size());
        List<String> deduplication = set.stream().sorted(Comparator.comparingInt(SlowQueryMetadata::getCount).reversed()).map(SlowQueryMetadata::toString).collect(Collectors.toList());
        FileUtils.write2File(new File(deduplicationFileFullName), deduplication);


    }

    private static List<SlowQueryMetadata> getSqlDTOList(List<String> list, String fileName) {
        List<SlowQueryMetadata> slowQueryMetadataList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String line = list.get(i);
            if (!StringUtils.hasText(line)) {
                continue;
            }
            if (line.trim().startsWith("# Time:")) {
                SlowQueryMetadata slowQueryMetadata = new SlowQueryMetadata();
                slowQueryMetadata.setFileName(fileName);
                slowQueryMetadataList.add(slowQueryMetadata);
                slowQueryMetadata.setTime(line);
                boolean multilineComment = false;
                while (i < list.size() - 1) {
                    i++;
                    line = list.get(i);
                    // 处理多行注释
                    if (line.trim().contains("/*")) {
                        multilineComment = true;
                        continue;
                    }
                    if (line.trim().contains("*/")) {
                        multilineComment = false;
                        continue;
                    }
                    if (multilineComment) {
                        continue;
                    }
                    if (line.trim().startsWith("# Time:")) {
                        i--;
                        break;
                    }
                    if (line.startsWith("# User@Host:")) {
                        slowQueryMetadata.setUserAndHost(line);
                        evaluationAppName(line, slowQueryMetadata);
                    }
                    if (line.startsWith("# Schema:")) {
                        slowQueryMetadata.setSchema(line);
                    }
                    if (line.startsWith("# Query_time:")) {
                        slowQueryMetadata.setQueryTime(line);
                    }
                    if (line.startsWith("# Bytes_sent:")) {
                        slowQueryMetadata.setBytesSent(line);
                    }
                    if (line.startsWith("SET timestamp=")) {
                        slowQueryMetadata.setTimestamp(line);
                    }
                    if (line.toLowerCase().trim().startsWith("insert") || line.toLowerCase().trim().startsWith("delete") || line.toLowerCase().trim().startsWith("update") || line.toLowerCase().trim().startsWith("select")) {
                        StringBuilder sql = new StringBuilder(line);
                        while (i < list.size() - 1) {
                            i++;
                            line = list.get(i);
                            if (line.startsWith("# Time: ")) {
                                i--;
                                break;
                            }
                            if (StringUtils.hasText(line) && !line.trim().startsWith("--")) {
                                sql.append(line);
                            }
                        }
                        slowQueryMetadata.setSql(sql.toString());
                        break;
                    }
                }
            }
        }
        return slowQueryMetadataList;
    }

    private static void evaluationAppName(String line, SlowQueryMetadata slowQueryMetadata) {
        try {
            // # User@Host: root[root] @  [192.168.100.101]  Id: 13523930
            String ip = line.substring(line.lastIndexOf("[")+1,line.lastIndexOf("]"));

            Map<String, String> appMap = getAppMap();
            String appName = appMap.get(ip);
            if (!StringUtils.hasText(appName)) {
                appName = "未知服务";
            }
            slowQueryMetadata.setAppName(appName);
        } catch (Exception e) {
            slowQueryMetadata.setAppName("异常服务");
        }

    }
    private static Map<String, String> getAppMap() {
        Map<String, String> appMap = new HashMap<>();
        appMap.put("192.168.100.101", "com-study-gateway");
        appMap.put("192.168.100.102", "com-study-gateway");
        appMap.put("192.168.100.103", "com-study-registry");
        appMap.put("192.168.100.104", "com-study-registry");
        appMap.put("192.168.100.104", "com-study-obs-web");
        appMap.put("192.168.100.106", "com-study-uid-web");
        return appMap;
    }

}

